import time
import datetime
from datetime import date, timedelta

import calendar
import os
import hashlib
import translation
from google.appengine.api import users
from google.appengine.ext.webapp import template
from django.utils import simplejson
from urlparse import urlparse
from google.appengine.api import mail
from google.appengine.api import memcache
import re #preg_replace
import webapp2 #2

from models import *

def t(text):
  lang = get_variable('lang', 'en')
  msgs=translation.s['en']
  for i in range(len(msgs)):
    if (text == msgs[i]):
      return translation.s[lang][i]
  return text

def get_variable(name, default):
  res = webapp2.get_app().registry.get(name)
  if not(res):
    return default
  return res

def set_variable(name, value):
  res = webapp2.get_app().registry[name] = value
  return res

def url(path):
  lang = get_variable('lang', 'en')
  return '/'+lang+path

def render(template_name,data):
    path = os.path.join(os.path.dirname(__file__), 'templates/'+template_name+'.html')
    content = template.render(path, data);
    return content;

def write_json(self, data):
  self.response.headers['Content-Type'] = 'application/json'
  self.response.out.write(simplejson.dumps(data))
  return

def get_token(val):
  solt = 'VA5ILY';
  return hashlib.sha1(solt+str(val)).hexdigest();

def valid_token(token, val):
  return token==get_token(val);

def generate_lang_menu(self):
  p = urlparse(self.request.url)
  path = p.path
  lang = get_variable('lang', 'en')
  menu = []
  for language in translation.languages():
    url_str = re.sub('^/'+lang, '/'+language, path)
    url_str = '/'+language+'/save-lang?destination='+url_str
    menu.append({'text': translation.name[language], 'url':url_str })
  return menu

def generate_menu(self):
   user = users.get_current_user()
   if not(user):
     menu = [
#     {'text': 'Login', 'url':users.create_login_url('')}
     ]
   else:
     p = urlparse(self.request.url);
     menu = [
     {'text': t('Stats'), 'url':url('/stats')},
     {'text': t('Settings'), 'url':url('/settings')},
     {'text': t('Logout'), 'url': users.create_logout_url(url('?logout=Y'))},
     ]
     for e in menu:
       if (e['url']==p.path):
          e['active']=True
          break
          
   return menu

def send_mail_in(user):
  user_from_users = get_user_CURRENT(user)
  user_settings = get_settings(user)
  if hasattr(user_settings, 'employer_emails'):
    from_addr = 'noreply@working-time.appspotmail.com'
    to_addr = user_settings.employer_emails
    if (mail.is_email_valid(to_addr)):

      come_title = user_settings.come_title.encode('utf8')
      if (come_title is None):
        come_title = t('I come')
      come_title = user_from_users.username.encode('utf8') + ' - ' + come_title  

      come_text = user_settings.come_text
      if (come_text is None):
            come_text = ''

      message = mail.EmailMessage()
      message.sender = from_addr
      message.to = to_addr
      message.subject = come_title
      message.body = come_text.encode('utf8')+'''

      ______
      Watch your working time with working-time.appspot.com
      '''
      message.send()



def send_mail_out(user):
  user_from_users = get_user_CURRENT(user)
  user_settings = get_settings(user)
  if hasattr(user_settings, 'employer_emails'):
    from_addr = 'noreply@working-time.appspotmail.com'
    to_addr = user_settings.employer_emails
    if mail.is_email_valid(to_addr):
      gone_title = user_settings.gone_title.encode('utf8')
      if (gone_title is None):
        gone_title = t('I gone')
      gone_title = user_from_users.username.encode('utf8') + ' - ' + gone_title 

      gone_text = user_settings.gone_text
      if (gone_text is None):
            gone_text = ''

      message = mail.EmailMessage()
      message.sender = from_addr
      message.to = to_addr
      message.subject = gone_title
      message.body = gone_text.encode('utf8')+'''

      ______
      Watch your working time with working-time.appspot.com
      '''
      message.send()
        

# memcache get/set
def get_lasttimeline(my_user, method='get'):
        mem_key = "timeline_"+my_user.user.email()

        if (method=='clear'):
            memcache.set(mem_key, None)
            return

        timeline = memcache.get(mem_key)
        if (timeline is not None):
            return timeline
        else:
            timeline = Timeline.all().filter('user =', my_user.user).order('-date_start').get()
            memcache.set(mem_key, timeline)
            return timeline
          
# memcache get/set
def get_user_byTOKEN(token, method='get'):
        mem_key = "token_user_"+token

        if (method=='clear'):
            memcache.set(mem_key, None)
            return

        user = memcache.get(mem_key)
        if (user is not None):
            return user
        else:
            user = Users.all().filter('auth_token =', token).get()
            memcache.set(mem_key, user)
            return user
          
# memcache get/set
def get_user_CURRENT(simple_user, method='get'):
        mem_key = "current_user_"+simple_user.email()

        if (method=='clear'):
            memcache.set(mem_key, None)
            return

        user = memcache.get(mem_key)
        if (user is not None):
            return user
        else:
            user = Users.all().filter('user =', simple_user).get()
            memcache.set(mem_key, user)
            return user

# memcache get/set
def get_settings(user, method='get'):
        mem_key = "user_settings_"+user.email()

        if (method=='clear'):
            memcache.set(mem_key, None)
            return

        user_settings = memcache.get(mem_key)
        if (user_settings is not None):
            return user_settings
        else:
            user_settings = Settings.all().filter('user =', user).get()
            memcache.set(mem_key, user_settings)
            return user_settings

def get_calendar_start(cur_date):
    cal = calendar.Calendar(0)
    month = cal.monthdatescalendar(cur_date.year, cur_date.month)
    firstweek = month[0]
    monday = firstweek[0]

    monday_tmstmp = int(time.mktime(monday.timetuple()))
    return monday_tmstmp

def get_timelinedata(email, start_stamp, finish_stamp, method='get'):
    mem_key = "timelinedata_"+email+'_'+str(start_stamp)

    if (method=='clear'):
        memcache.set(mem_key, None)
        return

    timeline = memcache.get(mem_key)
    if (timeline is not None):
        return timeline
    else:
        start = datetime.datetime.fromtimestamp(start_stamp)
        end = datetime.datetime.fromtimestamp(finish_stamp)
        timeline = Timeline.all().filter('user =', users.get_current_user()).filter('date_start >=', start).filter('date_start <=', end).fetch(1000)
        memcache.set(mem_key, timeline)
        return timeline